package com.itisyue.config;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.auth0.jwt.interfaces.Claim;
import com.itisyue.constant.RequestKeyConstants;
import com.itisyue.enums.ResponseCodeEnum;
import com.itisyue.utils.JWTUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.function.Consumer;

/**
 * https://www.cnblogs.com/cjsblog/p/12425912.html
 */
@Component
public class DemoFilter implements GlobalFilter, Ordered{
    private static Logger log = LoggerFactory.getLogger(DemoFilter.class);

    @Value("${jwt.secretKey}")
    private String secretKey;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //放行任何
        if(1>0){
            return chain.filter(exchange);
        }


//        log.info("demo global filter");
//        String str = exchange.getRequest().getQueryParams().getFirst("str");
////        if (null == str) {
////            // 若请求参数为null，则返回一个状态码，前台处理，否则继续执行后续的操作
////            ServerHttpResponse response = exchange.getResponse();
////            boolean b = response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
////            if (b) {
////                return exchange.getResponse().setComplete();
////            }
////        }
//        return chain.filter(exchange);


        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().toString();
        log.info("url={}",url);
        boolean contains = url.contains("/login");
        if(contains){
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst(RequestKeyConstants.TOKEN);
        //检查token是否为空
        if (StringUtils.isEmpty(token)) {
            return denyAccess(exchange, ResponseCodeEnum.TOKEN_NULL);
        }

        Map claimMap1 = JWTUtils.parseJwt(token, secretKey);
        //token有误
        if (claimMap1.containsKey("exception")) {
            log.error((claimMap1.get("exception").toString()));
            return denyAccess(exchange, ResponseCodeEnum.TOKEN_INVALID);
        }

        //token无误，将用户信息设置进header中,传递到下游服务
        Map<String, Claim> claimMap = claimMap1;
        String userId = claimMap.get(RequestKeyConstants.USER_ID).asString();
        Consumer<HttpHeaders> headers = httpHeaders -> {
            httpHeaders.add(RequestKeyConstants.USER_ID, userId);
        };
        request.mutate().headers(headers).build();

        return chain.filter(exchange);
 
    }

    /**
     * 拦截并返回自定义的json字符串
     */
    private Mono<Void> denyAccess(ServerWebExchange exchange, ResponseCodeEnum resultCode) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        //这里在返回头添加编码，否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSON.toJSONBytes(resultCode, SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }
 
    @Override
    public int getOrder() {
        return -1;
    }
}